package baduga.karo;
import baduga.core.*;

import java.awt.Color;
import java.awt.List;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.swing.UIManager;

import java.awt.Toolkit;

import javax.swing.JButton;
import javax.swing.GroupLayout.Alignment;
import javax.swing.GroupLayout;
import javax.swing.LayoutStyle.ComponentPlacement;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;




//Klasa klienta laczacego sie z serwerem na wybranym porcie.

/**
 * @author Karolina
 */
public class LoginScreen extends javax.swing.JFrame {

	private static final long serialVersionUID = 1L;

	//tworzymy okienko aplikacji
	
    public LoginScreen() {
		setIconImage(Toolkit.getDefaultToolkit().getImage(LoginScreen.class.getResource("/baduga/karo/resources/icon.png")));
        initComponents();
    }
    
    //tworzymy okienko z jego kolejnymi elementami
    
    private void initComponents() {

        menuBar1 = new java.awt.MenuBar();
        menu1 = new java.awt.Menu();
        menu2 = new java.awt.Menu();
        menuBar2 = new java.awt.MenuBar();
        menu3 = new java.awt.Menu();
        menu4 = new java.awt.Menu();
        menuBar3 = new java.awt.MenuBar();
        menu5 = new java.awt.Menu();
        menu6 = new java.awt.Menu();
        jLabelAddressPort = new javax.swing.JLabel();
        jTextFieldIP = new javax.swing.JTextField();
        jTextFieldPort = new javax.swing.JTextField();
        jLabelSeparator = new javax.swing.JLabel();
        jLabelNick = new javax.swing.JLabel();
        jTextFieldNick = new javax.swing.JTextField();
        jButtonPlay = new javax.swing.JButton();
        jLabelConnectionInfo = new javax.swing.JLabel();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenuFile = new javax.swing.JMenu();
        jMenuItemExit = new javax.swing.JMenuItem();
        jMenu = new javax.swing.JMenu();
        jMenuItemHelp = new javax.swing.JMenuItem();
        jMenuItemAbout = new javax.swing.JMenuItem();

        menu1.setLabel("File");
        menuBar1.add(menu1);

        menu2.setLabel("Edit");
        menuBar1.add(menu2);

        menu3.setLabel("File");
        menuBar2.add(menu3);

        menu4.setLabel("Edit");
        menuBar2.add(menu4);

        menu5.setLabel("File");
        menuBar3.add(menu5);

        menu6.setLabel("Edit");
        menuBar3.add(menu6);

        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        setTitle("Badugi - Logowanie");
        setResizable(false);

        jLabelAddressPort.setText("Adres IP serwera i port:");

        jTextFieldIP.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        jTextFieldIP.setText("127.0.0.1");

        jTextFieldPort.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        jTextFieldPort.setText(""+Core_Game_Cfg.DEFAULT_PORT);

        jLabelSeparator.setText(":");

        jLabelNick.setText("Podaj swój nick:");

        //losujemy dwie liczby co z duza szansa da nam wolnego nicka
        
        int first = (int)(Math.random() * 100);
        int second = (int)(Math.random()*100);
        
        int nickaddition = first * second * first * second;      
        
        jTextFieldNick.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        jTextFieldNick.setText("Player"+nickaddition);
        
        //obsługa przyciski "zagraj"
        
        jButtonPlay.setText("ZAGRAJ");
        jButtonPlay.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonPlayActionPerformed(evt);
            }
        });

        jLabelConnectionInfo.setText("Zagraj z nami w Badugi!");

        //elementy menu pod paskiem tytułu
        
        jMenuFile.setText("Plik");

        jMenuItemExit.setText("Zakończ");
        jMenuItemExit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItemExitActionPerformed(evt);
            }
        });
        jMenuFile.add(jMenuItemExit);

        jMenuBar1.add(jMenuFile);

        jMenu.setText("Pomoc");

        jMenuItemHelp.setText("Help");
        jMenu.add(jMenuItemHelp);

        jMenuItemAbout.setText("About");
        jMenuItemAbout.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItemAboutActionPerformed(evt);
            }
        });
        jMenu.add(jMenuItemAbout);

        jMenuBar1.add(jMenu);

        setJMenuBar(jMenuBar1);
        
        //przycisk czyści wpisane domyślnie wartości
        
        JButton btnWyczy = new JButton("Wyczyść");
        btnWyczy.addActionListener(new ActionListener() {
        	public void actionPerformed(ActionEvent arg0) {
        		jTextFieldNick.setText("");
        		jTextFieldPort.setText("");
        		jTextFieldIP.setText("");
        	}
        });
        
        JButton btnDomylne = new JButton("Domyślne");
        btnDomylne.addActionListener(new ActionListener() {
        	public void actionPerformed(ActionEvent arg0) {
        		jTextFieldNick.setText("Player"+nickaddition);
        		jTextFieldPort.setText(""+Core_Game_Cfg.DEFAULT_PORT);
        		jTextFieldIP.setText("127.0.0.1");
        	}
        });

        //parametry wyglądu okna
        
        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        layout.setHorizontalGroup(
        	layout.createParallelGroup(Alignment.TRAILING)
        		.addGroup(layout.createSequentialGroup()
        			.addContainerGap()
        			.addGroup(layout.createParallelGroup(Alignment.TRAILING)
        				.addComponent(jTextFieldNick, GroupLayout.PREFERRED_SIZE, 167, GroupLayout.PREFERRED_SIZE)
        				.addGroup(layout.createParallelGroup(Alignment.LEADING)
        					.addGroup(layout.createSequentialGroup()
        						.addComponent(jLabelAddressPort)
        						.addPreferredGap(ComponentPlacement.UNRELATED)
        						.addComponent(jTextFieldIP, GroupLayout.PREFERRED_SIZE, 102, GroupLayout.PREFERRED_SIZE)
        						.addGap(7)
        						.addComponent(jLabelSeparator)
        						.addPreferredGap(ComponentPlacement.RELATED)
        						.addComponent(jTextFieldPort, GroupLayout.PREFERRED_SIZE, 48, GroupLayout.PREFERRED_SIZE))
        					.addComponent(jLabelNick)))
        			.addContainerGap(28, Short.MAX_VALUE))
        		.addGroup(layout.createSequentialGroup()
        			.addContainerGap(11, Short.MAX_VALUE)
        			.addGroup(layout.createParallelGroup(Alignment.TRAILING, false)
        				.addGroup(layout.createSequentialGroup()
        					.addComponent(jLabelConnectionInfo)
        					.addGap(89))
        				.addGroup(layout.createSequentialGroup()
        					.addComponent(btnDomylne, GroupLayout.PREFERRED_SIZE, 83, GroupLayout.PREFERRED_SIZE)
        					.addPreferredGap(ComponentPlacement.RELATED)
        					.addComponent(btnWyczy, GroupLayout.PREFERRED_SIZE, 83, GroupLayout.PREFERRED_SIZE)
        					.addGap(35)
        					.addComponent(jButtonPlay, GroupLayout.PREFERRED_SIZE, 113, GroupLayout.PREFERRED_SIZE)
        					.addGap(30))))
        );
        layout.setVerticalGroup(
        	layout.createParallelGroup(Alignment.LEADING)
        		.addGroup(layout.createSequentialGroup()
        			.addContainerGap()
        			.addGroup(layout.createParallelGroup(Alignment.BASELINE)
        				.addComponent(jLabelAddressPort)
        				.addComponent(jTextFieldIP, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
        				.addComponent(jTextFieldPort, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
        				.addComponent(jLabelSeparator))
        			.addGap(18)
        			.addGroup(layout.createParallelGroup(Alignment.BASELINE)
        				.addComponent(jLabelNick)
        				.addComponent(jTextFieldNick, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
        			.addGroup(layout.createParallelGroup(Alignment.LEADING)
        				.addGroup(layout.createSequentialGroup()
        					.addGap(18)
        					.addGroup(layout.createParallelGroup(Alignment.BASELINE)
        						.addComponent(btnWyczy, GroupLayout.PREFERRED_SIZE, 23, GroupLayout.PREFERRED_SIZE)
        						.addComponent(btnDomylne)))
        				.addGroup(Alignment.TRAILING, layout.createSequentialGroup()
        					.addPreferredGap(ComponentPlacement.RELATED)
        					.addComponent(jButtonPlay, GroupLayout.PREFERRED_SIZE, 35, GroupLayout.PREFERRED_SIZE)))
        			.addPreferredGap(ComponentPlacement.RELATED)
        			.addComponent(jLabelConnectionInfo)
        			.addGap(24))
        );
        getContentPane().setLayout(layout);

        pack();
    }

    
     //metoda obslugujaca przycisk "Wyslij"     

    private void jButtonPlayActionPerformed(java.awt.event.ActionEvent evt) {

        int nickLen = jTextFieldNick.getText().length();
        String nick = jTextFieldNick.getText();
        if (nickLen == 0 || 3 > nickLen || nickLen > 60 ) {
            jLabelConnectionInfo.setText("Zła długość nicka");
            jLabelConnectionInfo.setForeground(Color.red);
            return;
        }
        
    //komunikaty błędu dla niepoprawnych danych
        
        if(!validateConnectionData(jTextFieldIP.getText(), jTextFieldPort.getText())){
            jLabelConnectionInfo.setText("Zły adres lub port");
            jLabelConnectionInfo.setForeground(Color.red);
        } else {
            jLabelConnectionInfo.setText("Trwa łączenie...");
            jLabelConnectionInfo.setForeground(new Color(0, 128, 0));
            
           
            String ip = jTextFieldIP.getText();
            String port = jTextFieldPort.getText();
            
            
             
            
            
     //jeśli logowanie udało się, otwieramy okienko z listą stołów
     
            
            final TableListScreen guiTable = new TableListScreen();
            guiTable.setVisible(true);
            guiTable.setLocationRelativeTo(null);
            this.dispose();
            
            
        }
        
    }
    //obsługa pozycji "wyjście", "o autorach"
    
    private void jMenuItemExitActionPerformed(java.awt.event.ActionEvent evt) {
         final ExitScreen question = new ExitScreen();
            question.setVisible(true);
            question.setLocationRelativeTo(null);
    }

    
    
  
    
    private void jMenuItemAboutActionPerformed(java.awt.event.ActionEvent evt) {
        final AboutAuthorsScreen about = new AboutAuthorsScreen();
            about.setVisible(true);
            about.setLocationRelativeTo(null);
    }
    
    //przekazanie IP, portu i nazwy uzytkownika
    
    

    public static void main(String args[]) {
    	
    	//zmieniamy styl okienek, jeżeli ten będzie niedostępny ładowany jest domyślny
    	
        try {
        javax.swing.UIManager.LookAndFeelInfo[] installedLookAndFeels=javax.swing.UIManager.getInstalledLookAndFeels();
            for (UIManager.LookAndFeelInfo installedLookAndFeel : installedLookAndFeels) {
                if ("Windows".equals(installedLookAndFeel.getName())) {
                    javax.swing.UIManager.setLookAndFeel(installedLookAndFeel.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(LoginScreen.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                final LoginScreen frame = new LoginScreen();                
                frame.setVisible(true);
                frame.setLocationRelativeTo(null);                
                frame.addWindowListener(new java.awt.event.WindowAdapter() {
    
    
});
     
                //Przy wyjściu z aplikacji następuje rozłączenie z serwerem

                //zamknięcie okna z komunikatem potwierdzającym
                
                frame.addWindowListener(
                        new java.awt.event.WindowAdapter() {
                            @Override
                            public void windowClosing(java.awt.event.WindowEvent e) {
                                final ExitScreen question = new ExitScreen();
                                question.setVisible(true);
                                question.setLocationRelativeTo(null);
                              
                                
                            }
                        }
                );
                
                
            }
            
        });
    }


    private javax.swing.JButton jButtonPlay;
    private javax.swing.JLabel jLabelAddressPort;
    private javax.swing.JLabel jLabelConnectionInfo;
    private javax.swing.JLabel jLabelNick;
    private javax.swing.JLabel jLabelSeparator;
    private javax.swing.JMenu jMenu;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenu jMenuFile;
    private javax.swing.JMenuItem jMenuItemAbout;
    private javax.swing.JMenuItem jMenuItemExit;
    private javax.swing.JMenuItem jMenuItemHelp;
    private javax.swing.JTextField jTextFieldIP;
    private javax.swing.JTextField jTextFieldNick;
    private javax.swing.JTextField jTextFieldPort;
    private java.awt.Menu menu1;
    private java.awt.Menu menu2;
    private java.awt.Menu menu3;
    private java.awt.Menu menu4;
    private java.awt.Menu menu5;
    private java.awt.Menu menu6;
    private java.awt.MenuBar menuBar1;
    private java.awt.MenuBar menuBar2;
    private java.awt.MenuBar menuBar3;
  

 
    /**
     * 
     * @param textIp
     * @param textPort
     * @return
     */
    
    //sprawdzenie poprawnosci wpisanego adresu IP i portu
    
    private boolean validateConnectionData(String textIp, String textPort) {
        Pattern p = Pattern.compile("^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]?|[0-9]):([0-9]{1,4}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5])$");
        Matcher m = p.matcher(textIp + ":" + textPort);
        if (m.matches()) {
            return true;    
        }
        return false;
    }
}
